var path = require("path");
var fs = require("fs");
var uuid = require("uuid");

let {chromium} = require("playwright");
var {map} = require("./tools");

var browser,context;

(async function(){
    browser = await chromium.launch();
    context = await browser.newContext();
})();


const formatMap = map('A0,A1,A2,A3,A4,A5,A6');

/**
 * @param {{html:string,format?:string,rotate?:boolean}} avgs 
 * @returns 
 */
async function createPDF(avgs){
    if(!avgs.html){
        return false;
    }
    console.log(avgs.format);
    if(!avgs.format){
        
        console.log("执行了")
        avgs.format = "A4";
    }else{
        avgs.format = avgs.format.toUpperCase();
        if(!formatMap(avgs.format)){
            return false;
        }
    }
    avgs.rotate = !!avgs.rotate;
    var page;
    
    try{
        page = await context.newPage();
        await page.goto(path.normalize(avgs.html));
        await page.emulateMedia({media: 'screen'});

        let pdfname = uuid.v1() + ".pdf";
        let out = path.normalize(path.join(__dirname,"../public/pdf",pdfname));
        console.log(out);

        await page.pdf({
            path:out,
            printBackground:true,
            landscape:avgs.rotate,
            format:avgs.format,
            margin:{
                top:"10mm",
                left:"10mm",
                right:"10mm",
                bottom:"10mm"
            }
        });
        console.log("创建成功")
        let pdfFile = fs.readFileSync(out);
        fs.unlinkSync(out,(err)=>{
            console.log("文件移除失败！");
        });
        return {data:pdfFile,pdfname};
    }
    catch(e){
        if(page && typeof page.close === "function"){
            page.close();
        }
        console.log(e);
    }
}

module.exports = createPDF;